<?php

include FCPATH . 'application/controllers/backend/backend.php';

class Banner extends Backend {

    public function __construct() {
	parent::__construct();

	$this->load->model('banner_model', 'model');
    }

    public function index() {
	$this->rend('backend/banner_index_view');
    }

    public function records() {
	$page = intval($this->input->get('page'));
	$page_size = intval($this->input->get('pageSize'));
	$offset = ($page - 1) * $page_size;

	$this->json_back('XT001', '', array(
	    'total' => $this->model->total(),
	    'records' => $this->model->records($page_size, $offset)
	));
    }

    public function insert() {
	$config = array(
	    'upload_path' => FCPATH . 'assets/uploads/banner/',
	    'allowed_types' => 'gif|jpg|png|bmp',
	    'max_size' => '2048',
	    'max_width' => '1024',
	    'max_height' => '1024',
	    'encrypt_name' => true
	);

	if (!file_exists($config['upload_path'])) {
	    mkdir($config['upload_path'], 0777);
	}

	$this->load->library('upload', $config);

	if (!$this->upload->do_upload('image')) {
	    $this->upload_back('XT002', $this->upload->display_errors());
	} else {
	    $upload_data = $this->upload->data();
	}

	$data = array(
	    'image' => $upload_data['file_name']
	);

	if ($this->model->insert($data)) {
	    $this->upload_back('XT001','上传成功');
	} else {
	    $this->upload_back('XT002', 'database error.');
	}
    }

    public function delete() {
	$id = intval($this->uri->segment(4));

	$banner = $this->model->find($id);

	$image = FCPATH . 'assets/uploads/banner/' . $banner->image;
	if (file_exists($image)) {
	    @unlink($image);
	}

	if ($this->model->delete_batch($id)) {
	    $this->json_back('XT001');
	} else {
	    $this->json_back('XT002', 'database error.');
	}
    }

}